<template>
  <el-dialog title="分配权限" center width="30%" :visible="showPermDialog" @close="close">
    <el-tree
      ref="tree"
      :data="treeList"
      show-checkbox
      node-key="id"
      :props="defaultProps"
      check-strictly
      default-expand-all
    />
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" size="mini" @click="assignPerm">确 定</el-button>
      <el-button size="mini" @click="close">取 消</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getPerm } from '@/api/permissions'
import { listToTree } from '@/utils'
import { getRolesDetails, updateRoles } from '@/api/roles'
export default {
  props: {
    showPermDialog: {
      type: Boolean,
      default: false
    },
    id: {
      type: Number,
      default: null
    }
  },
  data() {
    return {
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      treeList: [], // 权限列表
      permIds: [] // 选中的权限列表
    }
  },
  created() {
    this.getPermList()
  },
  methods: {
    async getPermList() { // 获取权限列表
      const res = await getPerm()
      this.treeList = listToTree(res.data, 0)
      // console.log(this.treeList)
    },
    // 数据回显已近选中的权限点
    getRoles() {
      this.$nextTick(async() => {
        const res = await getRolesDetails(this.id)
        console.log(57, res)
        this.permIds = res.data.permissions
        this.$refs.tree.setCheckedNodes(this.permIds)
      })
    },
    // 确认分配权限
    async assignPerm() {
      this.permIds = this.$refs.tree.getCheckedKeys()
      await updateRoles({
        id: this.id,
        permissions: this.permIds
      })
      // 提示
      this.$message.success('分配权限成功')
      // 关闭弹窗
      this.close()
    },
    // 关闭弹窗
    close() {
      this.$emit('update:showPermDialog', false)
      this.permIds = []
    }
  }
}
</script>

<style>

</style>
